<template>
  <div style="height: 100%" ref="echart"></div>
</template>

<script>
import * as echarts from "echarts";
export default {
  props: {
    // 父组件传来的数据
    chartData: {
      type: Object,
      default() {
        return {
          xData: [],
          series: [],
        };
      },
    },
    // 判断是否有坐标轴
    isAxisChart: {
      type: Boolean,
      // 默认有坐标轴
      default: true,
    },
  },
  computed: {
    // 判断使用配置数据的类型是有坐标轴的还是没有坐标轴的
    options() {
      return this.isAxisChart ? this.axisOption : this.normalOption;
    },
  },

  data() {
    return {
      // 初始化echart实例对象
      echart: null,
      // 有坐标轴数据
      axisOption: {
        xAxis: [],
        // 提示框
        tooltip: {
          trigger: "axis",
        },

        yAxis: [
          {
            type: "value",
          },
        ],
        series: [],
      },
      // 没有坐标轴数据
      normalOption: {
        // 图例
        legend: {
          // 图例布局方向
          orient: "vertical",
          icon: "circle",
          x: "right",
          y: "center",
          textStyle: {
            // 图例字体颜色
            color: "#333",
          },
        },
        tooltip: {
          trigger: "item",
        },
        series: [],
      },
    };
  },
  methods: {
    // 初始化echart实例对象
    initChart() {
      // 初始化图表数据
      this.initChartData();
      if (this.echart) {
        this.echart.setOption(this.options);
      } else {
        this.echart = echarts.init(this.$refs.echart);
        this.echart.setOption(this.options);
      }
    },
    // 初始化图表数据
    initChartData() {
      // 判断是否有坐标轴并指定数据
      if (this.isAxisChart) {
        this.axisOption.xAxis = this.chartData.xData;
        this.axisOption.series = this.chartData.series;
      } else {
        this.normalOption.series = this.chartData.series;
      }
    },

    // 图表自适应
    resizeChart() {
      this.echart ? this.echart.resize() : "";
    },
  },

  mounted() {
    this.initChart();
    window.addEventListener("resize", this.resizeChart);
  },
  destroyed() {
    window.removeEventListener("resize", this.resizeChart);
  },
};
</script>